# -*- coding: utf-8 -*-
#    Copyright (C) 2012  Ruslan V. Us <unclerus@gmail.com>, Aleksandr V. Bannov <kokudzin@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys, datetime, logging.handlers

class Log (object):

    def __init__ (self, name, filename):
        self._logger = logging.getLogger (name)
        self._logger.setLevel (logging.DEBUG)
        handler = logging.handlers.TimedRotatingFileHandler (filename, 'midnight')
        handler.setLevel (logging.DEBUG)
        handler.setFormatter (logging.Formatter ("%(message)s"))
        self._logger.addHandler (handler)
    
    def formatExc (self):
        try:
            exc = sys.exc_info ()
            if exc == (None, None, None):
                return ''
            import traceback
            return ''.join (traceback.format_exception (*exc))
        finally:
            del exc

    def error (self, msg = '', context = '', severity = logging.INFO, traceback = False):
        now = datetime.datetime.now ()
        if traceback:
            msg += self.formatExc ()
        self._logger.log (
            severity,
            ' '.join ((
                now.strftime ('[%Y-%m-%d %H:%M:%S]'),
                context,
                msg
            ))
        )
    
    def notice (self, msg):
        self.error (msg)